package com.jintoufs.interceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.cosmos.modules.web.utils.ServletUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

/**
 * @author fisher
 * @description 全局异常处理
 */

public class GlobalExceptionResolver extends SimpleMappingExceptionResolver {
	private Log log= LogFactory.getLog(GlobalExceptionResolver.class);
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {

		// Expose ModelAndView for chosen error view.  
		String viewName = determineViewName(ex, request);
		log.error(ex);
		if (viewName != null) {
			//--普通异常跳转到JSP页面--//
			if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
					.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").indexOf(
					"XMLHttpRequest") > -1))||request.getParameter("blank")!=null) {
				// Apply HTTP status code for error views, if specified.  
				// Only apply it if we're processing a top-level request.  
				
				Integer statusCode = determineStatusCode(request, viewName);
				if (statusCode != null) {
					applyStatusCodeIfPossible(request, response, statusCode);
				}
				return getModelAndView(viewName, ex, request);
			} else {
				//-- 异步请求以JSON格式返回--  
				AjaxMsg ajaxMsg = new AjaxMsg();
				ajaxMsg.setMessage(ex.getMessage());
				ajaxMsg.setCode(AjaxMsg.FAILURE);
				ServletUtils.renderJson(response, ajaxMsg);

				return null;
			}
		} else {
			return null;
		}
	}
}
